//
//  DetailViewController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

class ProductPayController: UIViewController, HttpProtocol, WXApiManagerDelegate {
    
    //设置商品的属性
    @IBOutlet weak var productName: UILabel!
    @IBOutlet weak var productType: UILabel!
    @IBOutlet weak var productPrice: UILabel!
    @IBOutlet weak var productPostage: UILabel!
    @IBOutlet weak var productImage: UIImageView!
    
    //设置收货地址
    @IBOutlet weak var Addressee: UILabel!
    @IBOutlet weak var CellPhone: UILabel!
    @IBOutlet weak var ReceiptAddress: UILabel!
    
    var productID:String?
    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    
    var eHttp:HTTPController = HTTPController()
    
    /* 重写
    + (NSString *)jumpToBizPay {
    
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
    NSMutableDictionary *dict = NULL;
    //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
    dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    
    NSLog(@"url:%@",urlString);
    if(dict != nil){
    NSMutableString *retcode = [dict objectForKey:@"retcode"];
    if (retcode.intValue == 0){
    NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
    
    //调起微信支付
    PayReq* req             = [[[PayReq alloc] init]autorelease];
    req.partnerId           = [dict objectForKey:@"partnerid"];
    req.prepayId            = [dict objectForKey:@"prepayid"];
    req.nonceStr            = [dict objectForKey:@"noncestr"];
    req.timeStamp           = stamp.intValue;
    req.package             = [dict objectForKey:@"package"];
    req.sign                = [dict objectForKey:@"sign"];
    [WXApi sendReq:req];
    //日志输出
    NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
    return @"";
    }else{
    return [dict objectForKey:@"retmsg"];
    }
    }else{
    return @"服务器返回错误，未获取到json对象";
    }
    }else{
    return @"服务器返回错误";
    }
    }
    
    */
    
    


    override func viewDidLoad() {
        super.viewDidLoad()
        
        WXApiManager.sharedManager().delegate = self
        
        navigationItem.title = "商品支付"
        eHttp.delegate = self
        
        //在这里进行请求产品ID
        let geturl = "http://42.62.18.210:8090/apiradio/ar/getOrder?orderID="+productID!
        
        print(geturl)
        eHttp.onsearch(geturl)
        //self.tabBarController!.tabBar.hidden = true;
        
        //这里获取收货人的默认地址
        let urladdress = "http://42.62.18.210:8090/apiradio/ar/getDefaultAddr?userID="+keychain.get("registerUserID")!
        print(urladdress)
        Alamofire.request(.GET, urladdress)
            .responseJSON { response in
                if let result = response.result.value {
                    //
                    print(result)
                    let json = JSON(result)
                    
                    if String(json["msg"]) == "200" {
                        self.Addressee.text = String(json["obj"]["name"])
                        self.CellPhone.text = String(json["obj"]["phoneNumber"])
                        self.ReceiptAddress.text = String(json["obj"]["address"])
                    }
                }
        }
    }
    
    @IBAction func ConfirmPayment(sender: AnyObject) {
        //
        print("提交支付")
        
        /*
        let BaseUrl = "http://42.62.18.210:8090/apiradio/ar/wxprepay?orderID="+productID!
        Alamofire.request(.GET, BaseUrl).responseJSON { response in
        if let result = response.result.value {
        print(result)
        let json = JSON(result)
        if json["msg"] == "200" {
        
        }
        }
        }*/
        let BaseUrl = "http://42.62.18.210:8090/apiradio/ar/wxprepay?orderID="+productID!
        
        let _ = WXApiRequestHandler.jumpToBizPay(BaseUrl)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showAlert:", name:"NotificationIdentifier", object: nil)
        
        //let _ = WXApiRequestHandler.jumpToBizPay(BaseUrl)
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "showAlert:", name:"NotificationIdentifier", object: nil)
        
    }
    
    
    /* 获取礼品数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        print("results: \(results)")
        let json = JSON(results)
        
        print("test")
        print(String(json["obj"]["goodsImg"]))

        
        if let picList = json["obj"]["goodsImg"].array {
            let rowData:JSON = picList[0]
            
            //获取图片
            let MusicImageUrl = "http://testimg.qichexiaozi.com/"+String(rowData["url"]);
            print("lanyaerji")
            print(MusicImageUrl)
            Alamofire.request(.GET, MusicImageUrl).response() {
                (_, _, data, _) in
                let image = UIImage(data: data! as NSData)
                self.productImage.image = image
            }
            
        }
        

        
        productName.text    = String(json["obj"]["goodsName"])
        productPrice.text   = String(json["obj"]["nowPrice"])+"元"
        productPostage.text = String(json["obj"]["oriPrice"])+"元"
        
    }
    
    func showAlert(notification:NSNotification){
        //获取词典中的值
        let code = Int((notification.object?.valueForKey("errCode") as! String))
        //notification.userInfo 接收object 对象 一些信息 例如入键盘的一些信息
        print(code!);
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillDisappear(animated: Bool) {
        //self.tabBarController!.tabBar.hidden = false;
    }
}
